<template>
    <div ref="container">
        <a-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading"
            :getContainer="() => $refs.container" :maskStyle="{'top':'93px','left':'154px'}"
            :wrapClassName="wrapClassNameInfo()" :mask="isDesktop()" :maskClosable="false" @ok="handleOk"
            @cancel="handleCancel" cancelText="关闭" style="top:5%;height: 95%;">
            <a-spin :spinning="confirmLoading">
                <a-form :form="form" id="userModal">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="comLabel">
                        <a-select :placeholder="comLabel" v-decorator="['bindUser', validatorRules.bindUser]"
                            :showSearch="true" :dropdownMatchSelectWidth="false" :filterOption="filterOption"
                            allowClear>
                            <a-select-option :disabled="item.linked" v-for="(item, index) in suppliersList"
                                :key="item.id" :value="item.id">
                                {{ item.title }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </a-spin>
        </a-modal>
    </div>
</template>
  <script>
import pick from "lodash.pick";
import { mixinDevice } from "@/utils/mixin";
import { addUserBusiness, editUserBusiness, checkUserBusiness } from "@/api/api";
import { getAction, putAction, postAction } from "@/api/manage";
import Vue from "vue";

const UBTypes = {
    1: "UserClient", // 绑定客户,
    2: "UserSupplier", // 绑定供应商,
};
export default {
    name: "BindingSuppliersModal",
    mixins: [mixinDevice],
    data() {
        return {
            title: "操作",
            visible: false,
            model: {},
            roleId: 0,
            iExpandedKeys: [],
            roleFunctionTree: [],
            checkedKeys: [],
            selectedKeys: [],
            checkStrictly: false,
            hiding: true,
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            confirmLoading: false,
            form: this.$form.createForm(this),
            suppliersList: [],
            currentRecord: {},
            validatorRules: {
                bindUser: {
                    rules: [{ required: true, message: "请选择供应商" }],
                },
            },
            extraParams: {},
        };
    },

    computed: {
        comLabel() {
            const labels = {
                1: "选择客户",
                2: "选择供应商",
            };
            return this.extraParams.handleType !== undefined ? labels[this.extraParams.handleType] : "未知";
        },
    },
    created() {},
    methods: {
        edit(record, extraParams = {}) {
            this.form.resetFields();
            this.model = Object.assign({}, {});
            this.visible = true;
            this.$nextTick(() => {
                this.form.setFieldsValue(pick(this.model, "bindUser"));
            });
            this.extraParams = extraParams;
            this.currentRecord = record;
            this.loadTree(record.id);
        },
        close() {
            this.$emit("close");
            this.form.resetFields();
            this.visible = false;
        },

        handleOk() {
            const that = this;
            // 触发表单验证
            this.form.validateFields(async (err, values) => {
                if (!err) {
                    let self = this;
                    let checkRes = await getAction(`userBusiness/checkIsValueExist?type=${UBTypes[this.extraParams.handleType]}&keyId=${this.currentRecord.id}`);
                    if (checkRes.code != 200) return;
                    that.confirmLoading = true;
                    // 选中用户，查询供应商列表，（接口[查询供应商列表] ），
                    //选中供应商（单选）保存，保存前调用校验接口（接口[校验用户是否存在绑定关系]）校验是否存在绑定关系
                    //如不存在调用接口[绑定供应商-add]如存在调用[绑定供应商-update]（是否存在区别在于校验接口中是否返回id）
                    if (checkRes.data.id) {
                        let params = {
                            type: UBTypes[this.extraParams.handleType],
                            keyId: this.currentRecord.id,
                            id: checkRes.data.id,
                            value: [values.bindUser],
                        };
                        putAction("/userBusiness/update", params)
                            .then((res) => {
                                if (res.code == 200) {
                                    this.$message.success("绑定成功");
                                    this.$emit("ok");
                                    this.$emit("clear");
                                } else {
                                    this.$message.warning(res.data.message);
                                }
                            })
                            .finally(() => {
                                this.confirmLoading = false;
                                self.close();
                            });
                    } else {
                        let params = {
                            type: UBTypes[this.extraParams.handleType],
                            keyId: this.currentRecord.id,
                            value: [values.bindUser],
                        };
                        postAction("/userBusiness/add", params)
                            .then((res) => {
                                if (res.code == 200) {
                                    this.$message.success("绑定成功");
                                    this.$emit("ok");
                                    this.$emit("clear");
                                } else {
                                    this.$message.warning(res.data.message);
                                }
                            })
                            .finally(() => {
                                self.confirmLoading = false;
                                self.close();
                            });
                    }
                }
            });
        },
        handleCancel() {
            this.close();
        },
        loadTree(id) {
            let that = this;
            let roleType = Vue.ls.get("roleType");

            getAction(`/supplier/findUserSupplier?UBType=${UBTypes[this.extraParams.handleType]}&UBKeyId=${id}&roleType=${roleType}`).then((res) => {
                if (res) {
                    that.suppliersList = res;
                    let checkedUserSupplier = that.suppliersList.find((item) => item.checked);
                    if (checkedUserSupplier && checkedUserSupplier.id) {
                        this.form.setFieldsValue({ bindUser: checkedUserSupplier.id });
                    }
                }
            });
        },

        filterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
    },
};
</script>
  <style scoped>
</style>